package durose.system.aop;

import java.lang.reflect.Method;
import java.util.Arrays;
import java.util.Date;

import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.Around;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.aspectj.lang.reflect.MethodSignature;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;

import durose.system.annotation.DuRoseLog;
import durose.system.pojo.Sys_log;
import durose.system.service.Sys_logService;

@Aspect
@Component
public class LogAop {
	
	@Autowired
	Sys_logService sys_logService;
	
    //指定切点
	@Pointcut(value = "execution(* durose.modular.controller.*.*(..))")
    public void cutService() {
    }
	
    @Around("cutService()")
    public Object log(ProceedingJoinPoint joinPoint) throws Throwable {
        Object object = joinPoint.proceed();
        insertLog(joinPoint,object);
        return object;
    }
    
    private void insertLog(ProceedingJoinPoint joinPoint, Object object) throws NoSuchMethodException, SecurityException{
    	Sys_log log = new Sys_log();
    	/**
    	 * 通过注解给日志增加name与descri
    	 */
    	//获得注解name 与des
    	//获取切点方法信息
    	MethodSignature msi = (MethodSignature)joinPoint.getSignature();
    	//获取被代理的对象
    	Object target = joinPoint.getTarget();
    	
    	//反射获取方法
    	Method m =target.getClass().getDeclaredMethod(msi.getName(), msi.getParameterTypes());
    	//获取方法上的注解
    	DuRoseLog logAnnotation = m.getAnnotation(DuRoseLog.class);
    	String url = Arrays.toString(m.getAnnotation(RequestMapping.class).value());
    	if(logAnnotation!=null){
    		log.setLog_name(logAnnotation.logName());
    		log.setLog_descri(logAnnotation.logDescri());
    	}else{
    		//如果没有注解描述的话，就把请求链接扔给介绍信息
    		log.setLog_name("未命名，可以通过注解命名");
    		log.setLog_descri("访问的url为"+url);
    	}
    	
    	/**
    	 * 给日志增加detail
    	 */
    	/**
    	 * 给日志增加记录时间
    	 */
    	log.setLog_date(new Date());
    	sys_logService.sys_logAdd(log);
    }
}